package com.example.smokealarm.service;

import com.example.smokealarm.model.LoginAccount;
import com.example.smokealarm.model.LoginRequest;
import com.example.smokealarm.model.LoginResponse;
import com.example.smokealarm.repository.LoginAccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class LoginAccountService {
    @Autowired
    private LoginAccountRepository repository;

    public List<LoginAccount> getAllAccounts() {
        return repository.findAll();
    }

    public LoginAccount createAccount(LoginAccount account) {
        return repository.save(account);
    }

    public LoginResponse login(LoginRequest loginRequest) {
        LoginResponse response = new LoginResponse();
        Optional<LoginAccount> account = repository.findByAccountAndPassword(loginRequest.getAccount(), loginRequest.getPassword());
        if (account.isPresent()) {
            response.setSuccess(true);
            response.setMessage("登录成功");
            response.setId(account.get().getId());
        } else {
            response.setSuccess(false);
            response.setMessage("账号或密码错误");
            response.setId(null);
        }
        return response;
    }

    public LoginResponse register(LoginAccount account) {
        LoginResponse response = new LoginResponse();
        if (repository.findByAccount(account.getAccount()).isPresent()) {
            response.setSuccess(false);
            response.setMessage("账号已存在");
        } else {
            repository.save(account);
            response.setSuccess(true);
            response.setMessage("注册成功");
        }
        return response;
    }
}